//
//  CercaViewController.m
//  FinApp
//
//  Created by Marcel Arbó Lack on 11/11/11.
//  Copyright (c) 2011 FIB-Fàcultat d'informàtica de Barcelona. All rights reserved.
//

#import "CercaViewController.h"
#import "RestConsumer.h"
#import "AppDelegate.h"
#import "LocationManager.h"
#import "ListFlat.h"
#import "CercaMapViewController.h"
#import "CercaListViewController.h"
#import "AugmentedRealityCamera.h"
#import "RotatingViewController.h"
#import "DetailRotatingViewController.h"
#import "DetailViewController.h"

@interface CercaViewController ()

- (void)buildSegmented;

@end

@implementation CercaViewController
@synthesize navigationBar = _navigationBar;
@synthesize containerView = _containerView;
@synthesize segmentedControl = _segmentedControl;
@synthesize flats = _flats;
@synthesize mapVC = _mapVC;
@synthesize listVC = _listVC;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"_cerca", @"");
        self.tabBarItem.image = [UIImage imageNamed:@"tabbar_icon_cerca"];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self buildSegmented];
    [self.navigationController setNavigationBarHidden:YES];
    
    _mapVC = [[CercaMapViewController alloc] initWithNibName:@"CercaMapViewController" bundle:nil];
    _listVC = [[CercaListViewController alloc] initWithNibName:@"CercaListViewController" bundle:nil];
    
    [_mapVC setParentVC:self];
    [_listVC setParentVC:self];
    [_containerView addSubview:_mapVC.view];
    
    UIBarButtonItem *arButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_ra", @"") style:UIBarButtonItemStyleBordered target:self action:@selector(openRA:)];
    [_navigationBar.topItem setLeftBarButtonItem:arButton];
    [arButton release];
    
    UIBarButtonItem *myPositionButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ico_geo.png"] style:UIBarButtonItemStyleBordered target:_mapVC action:@selector(returnMyPosition:)];
    [_navigationBar.topItem setRightBarButtonItem:myPositionButton];
    [myPositionButton release];

    // Busquem localització si no la tenim
    int latitude = [[LocationManager sharedInstance] myLocation].coordinate.latitude;
	int longitude = [[LocationManager sharedInstance] myLocation].coordinate.longitude;
    
    if ((latitude == 0 && longitude == 0)) {
        
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(newLocation:) 
													 name:@"positionUpdated"
												   object:[LocationManager sharedInstance]];
 
        [(AppDelegate*)[[UIApplication sharedApplication] delegate] showBigActivityWithText:NSLocalizedString(@"_buscantLocalitzacio", @"")];
	}
	else {
        [[RestConsumer sharedInstance] getHousesNearLatitude:latitude andLongitude:longitude withRadius:2000 page:1 andNumberPerPage:25 withDelegate:self];
        [(AppDelegate*)[[UIApplication sharedApplication] delegate] showBigActivityWithText:NSLocalizedString(@"_carregantPisos", @"")];
    }
}



- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    
    [_navigationBar release];
    [_containerView release];
    [_segmentedControl release];
    [_flats release];
    [_mapVC release];
    [_listVC release];
    
    [super dealloc];
    
}


- (void)showSubviews:(id)sender {
    UISegmentedControl *segmented = (UISegmentedControl*)sender;
    if ([segmented selectedSegmentIndex] == 0) {
        for (UIView * view in _containerView.subviews) {
            [view removeFromSuperview];
        }
        [_containerView addSubview:_mapVC.view];
        [_mapVC loadMap];
        UIBarButtonItem *arButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_ra", @"") style:UIBarButtonItemStyleBordered target:self action:@selector(openRA:)];
        [_navigationBar.topItem setLeftBarButtonItem:arButton];
        [arButton release];
        UIBarButtonItem *myPositionButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ico_geo.png"] style:UIBarButtonItemStyleBordered target:_mapVC action:@selector(returnMyPosition:)];
        [_navigationBar.topItem setRightBarButtonItem:myPositionButton];
        [myPositionButton release];
    } else {
        for (UIView * view in _containerView.subviews) {
            [view removeFromSuperview];
        }
        [_containerView addSubview:_listVC.view];
        [_navigationBar.topItem setRightBarButtonItem:nil];
        [_navigationBar.topItem setLeftBarButtonItem:nil];
    }
}

- (void)openRA:(id)sender {
    AugmentedRealityCamera *camera = [[AugmentedRealityCamera alloc] init];	
	[camera setArrayOfInformation:_flats];
	[camera setProviderDelegate:self];
	[camera setHidesBottomBarWhenPushed:YES];
	
	[self presentModalViewController:camera animated:YES];
    
    [camera release];
}

- (void) goToDetail:(ListFlat*)flat {
    DetailViewController *detailVC = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    [detailVC setFlat:(Flat*)flat];
    [detailVC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:detailVC animated:YES];
    [detailVC release];
}
         
#pragma mark - Private Methods

- (void) buildSegmented {
    //Add mySegmentedControl to navigationBar
    NSArray *segmentedItemsArray = [[NSArray alloc] initWithObjects:NSLocalizedString(@"_mapa",@""), NSLocalizedString(@"_llistat",@""), nil];
    _segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentedItemsArray];
    [segmentedItemsArray release];
    _segmentedControl.frame = CGRectMake(0, 0, 146, 30);
    _segmentedControl.tintColor = [UIColor blackColor];
    _segmentedControl.center = _navigationBar.center;
    _segmentedControl.segmentedControlStyle = UISegmentedControlStyleBezeled;
    _segmentedControl.selectedSegmentIndex = 0;
    [_segmentedControl addTarget:self action:@selector(showSubviews:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_segmentedControl];
}
#pragma mark - Location Methods
- (void)newLocation:(CLLocation*)newLocation {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    int latitude = [[LocationManager sharedInstance] myLocation].coordinate.latitude;
	int longitude = [[LocationManager sharedInstance] myLocation].coordinate.longitude;
	if ((latitude == 0 && longitude == 0)) {
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(newLocation:) 
													 name:@"positionUpdated"
												   object:[LocationManager sharedInstance]];
	}
	else {
        [[RestConsumer sharedInstance] getHousesNearLatitude:latitude andLongitude:longitude withRadius:2000 page:1 andNumberPerPage:25 withDelegate:self];
        [(AppDelegate*)[[UIApplication sharedApplication] delegate] removeBigActivity];
        [(AppDelegate*)[[UIApplication sharedApplication] delegate] showBigActivityWithText:NSLocalizedString(@"_carregantPisos", @"")];
	} 
}

#pragma mark -
#pragma mark AugmentedRealityCameraControllerProviderDelegate

// Devuelve un controlador para que sea una vista giratoria
- (ARRotatingViewController *)arControllerForARCoordinate:(ARCoordinate *)coordinate {
	
	RotatingViewController * rotatingView = [[[RotatingViewController alloc] initWithNibName:@"RotatingView" 
																					  bundle:nil] autorelease];
	
	// Establecemos el modo de funcionamiento

	[rotatingView setDistanceString:[NSString stringWithFormat:@"%.0fm",coordinate.radialDistance]];
	[rotatingView setAddressString:coordinate.aditionalInfo];
	
	return rotatingView;
}

// Devuelve un controlador para que sea el detalle de una vista. Estará fija en la pantalla al selecionar la vista gitaroria
- (ARDetailViewController *)arDetailControllerForARCoordinate:(ARCoordinate *)coordinate {
	
	DetailRotatingViewController * detailView = [[[DetailRotatingViewController alloc] initWithNibName:@"DetailRotatingView" 
                                                                                                bundle:nil] autorelease];

    [detailView setPriceString:coordinate.title];
	[detailView setDistanceString:[NSString stringWithFormat:@"%.0fm",coordinate.radialDistance]];
	[detailView setAddressString:coordinate.aditionalInfo];
    
	return detailView;	
}


#pragma mark - DataFetchingHandler

-(void)dataFetchingDidFailWithTag:(NSString*)tag andError:(NSError*)error {
    [(AppDelegate*)[[UIApplication sharedApplication] delegate] removeBigActivity];
}

-(void)dataFetchingCompleteWithTag:(NSString*)tag data:(id)aData andStatus:(NSInteger)status{
    NSDictionary *response = (NSDictionary*)aData;
    if ([[response objectForKey:@"responseCode"] intValue] != 200) {
        [self dataFetchingDidFailWithTag:tag andError:nil];
        return;
    }
    if ([tag isEqualToString:kNEARMETAG]) {
        //Get Data
        [(AppDelegate*)[[UIApplication sharedApplication] delegate] removeBigActivity];
        if (!_flats) {
            _flats = [[NSMutableArray alloc] init];
        }
        for (NSDictionary *flatDict in [response objectForKey:@"inmobles"]) {
            [_flats addObject:[ListFlat listFlatFromDictionary:flatDict]];
        }
        
        [_mapVC loadMap];
        
    }
}
@end
